<template>
    <div class="course-container">
        <a-spin :spinning="loading">
            <a-empty v-if="courses.length === 0" description="暂无课程数据" />

            <div v-else class="course-list">
                <a-card v-for="course in courses" :key="course.id" class="course-card" :title="course.title">
                    <template #extra>

                        <a-tag :color="statusColorMap[course.status]">
                            {{ statusTextMap[course.status] }}
                        </a-tag>

                    </template>

                    <div class="course-info">
                        <div class="info-item">
                            <span class="label">订单用户：</span>
                            {{ course.studentUsername }}
                        </div>
                        <div class="info-item">
                            <span class="label">联系方式：</span>
                            {{ course.studentMobile }}
                        </div>
                        <div class="info-item">
                            <span class="label">课程时间：</span>
                            {{ course.startTime.slice(0, 10) }} 至 {{ course.endTime.slice(0, 10) }}
                        </div>
                        <div class="info-item">
                            <span class="label">课时安排：</span>
                            {{ course.days }}天 × {{ course.hoursPerDay }}小时/天
                        </div>
                        <div class="amount-actions">
                            <div class="total-amount">总金额：¥{{ course.totalAmount }}</div>
                            <div v-if="course.status === 'PENDING'" class="action-buttons">
                                <a-button type="primary" @click="handleAccept(course.id)" size="small">接受</a-button>
                                <a-button danger @click="handleReject(course.id)" size="small">拒绝</a-button>
                            </div>


                            <div v-if="course.status === 'PROGRESS'">
                                <a-button v-if="!course.teacherConfirmed" type="primary"
                                    @click="handleTeacherConfirm(course.id)" size="small">确认完成该课程</a-button>
                                <a-tag v-else color="green" style="margin-left:8px">✓ 已确认，待家长确认</a-tag>
                            </div>
                        </div>
                    </div>
                </a-card>
            </div>
        </a-spin>

        
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { get } from '/@/utils/http/axios';
import type { CourseStatus } from '/@/api/course';
import { listTeacherCoursesApi } from '/@/api/course';
import { message } from 'ant-design-vue';
import { updateCourseStatusApi } from '/@/api/course';
import request from "/@/utils/http/axios";
import { useUserStore } from "/@/store";


interface Course {
    id: number;
    title: string;
    startTime: string;
    endTime: string;
    status: CourseStatus;
    studentUsername: string;
    studentMobile: string;
    hoursPerDay: number;
    days: number;
    totalAmount: number;

    studentConfirmed: boolean;
    teacherConfirmed: boolean;
}

const route = useRoute();
const loading = ref(false);
const courses = ref<Course[]>([]);
const userStore = useUserStore();

// 状态映射
const statusTextMap = {
    PENDING: '待确认',
    PROGRESS: '进行中',
    COMPLETED: '已完成',
    CANCELED: '已取消'
};

const statusColorMap = {
    PENDING: 'orange',
    PROGRESS: 'green',
    COMPLETED: 'blue',
    CANCELED: 'red'
};

// 监听路由名称变化
watch(
    () => route.name, // 监听路由name变化
    (newRouteName) => {
        if (newRouteName) {
            loadCourses();
        }
    }
);

// 获取课程数据
const loadCourses = async () => {
    try {
        loading.value = true;
        const statusMap: Record<string, CourseStatus> = {
            sure: 'PENDING',
            ing: 'PROGRESS',
            over: 'COMPLETED',
            canceled: 'CANCELED'
        };

        // 根据路由name获取状态
        const targetStatus = statusMap[route.name as string];
        const res = await listTeacherCoursesApi(targetStatus);
        
        courses.value = res;
    } catch (error) {
        console.error('加载课程失败:', error);
    } finally {
        loading.value = false;
    }
};


onMounted(() => {
    loadCourses();
});

const handleAccept = async (courseId: number) => {
    await updateCourseStatusApi(courseId, 'PROGRESS');
    message.success('已接受');
    loadCourses(); // 刷新列表
};

const handleReject = async (courseId: number) => {
    await updateCourseStatusApi(courseId, 'CANCELED');
    message.success('已拒绝');
    loadCourses(); // 刷新列表
};

const handleTeacherConfirm = async (courseId: number) => {
    try {
        await request({
            method: 'post',
            url: `/api/course/teacherConfirm/${courseId}`,
            params: { userId: userStore.user_id }
        });
        message.success('确认成功');
        loadCourses(); // 刷新列表
    } catch (error) {
        message.error('确认失败');
    }
};
</script>

<style scoped>
.course-container {
    padding: 20px;
}

.course-list {
    display: grid;
    gap: 16px;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}

.course-card {
    transition: all 0.3s;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
}

.course-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.info-item {
    margin: 8px 0;
    font-size: 14px;
}

.label {
    color: #666;
    font-weight: 500;
}

.total-amount {
    margin-top: 12px;
    padding-top: 12px;
    /* border-top: 1px solid #eee; */
    font-weight: 600;
    color: #1890ff;
    margin: 0;
}

.ant-empty {
    margin: 40px 0;
}

.amount-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 12px;
    padding-top: 12px;
    border-top: 1px solid #eee;
}

.action-buttons {
    display: flex;
    gap: 8px;
}
</style>